package com.secneo.appshare.activities;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsAdapter;
import com.secneo.appshare.adapter.PrivateMsgListAdapter;
import com.secneo.appshare.adapter.UserAppAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.Feeds;
import com.secneo.appshare.api.RemoteApi.OtherUserApps;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.AppInfo;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.privatemsg.PrivateMsg;
import com.secneo.appshare.threads.FeedsThread;
import com.secneo.appshare.threads.PrivateMsgThread;
import com.secneo.appshare.threads.RemindCountThread;
import com.secneo.appshare.threads.UserAppThread;
import com.secneo.mp.api.database.DatabaseHelper;

public class UserAppActivity extends CommonMenuActivity 
{
	
	enum UserAppPage{
		MyAppPage ,
		MyFlowPage ,
		MyFansPage ,
		MyPrivateMsgPage
	}
	
	private LinearLayout mBottomButtonLayout;
	
	private String uid;
	private String other_uid;
	private LinearLayout myInfoLinear;
	private GridView mAppGridView;
	private TextView label_user_name;
	private TextView phone_type;
	private ImageView img_user_icon;
	private ImageView weibo_Icon;
	private ProgressBar progress_user_apps;
	private PackageManager pm;
	private Button buttonApp;
	private Button buttonFollowed; 
	private Button buttonFollower;
	private Button buttonSms;
	private Button paixu;

	private TextView numFollowedText;
	private TextView numFollowerText;
	private TextView numInstallText;
	private TextView numShareText;

	private TextView textFollowed; 
	private TextView textFollower;
	private TextView textInstall; 
	private TextView textShare;
	
	private FeedsThread userFollowedThread = null;
	private FeedsThread userFollowerThread = null;
	
	private Button btnPrivateMessage;
	
	private Button mRetIv ;
	private TextView mTopbarTv;

	private TextView mShuziFollower,mShuziHonor;
	
	private PrivateMsgThread privateMsgThread ;	
	private ListView mPrivateMsgListView ;
	private TextView mEmptyListPromptTV ;
	
	private UserAppPage currentControl ;
	
	private ProgressDialog mDynDisPMProgressBar = null;
	private int mPrivateMsgPageIndex = 1 ;
	private boolean mMsgLoadOver = false ;
	private boolean mDialogListShow = false ;	//标示加载了对话列表
	private ArrayList<PrivateMsg> mPrivateMsgList = new ArrayList<PrivateMsg>() ;
	
	private ProgressDialog mDelMsgProgressBar = null;
	private PrivateMsgListAdapter adapter = null ;
	private FeedsAdapter feedAdapter = null;
	private RemindReciver mRemindReciver = null ;
	private UserAppThread userAppThread = null;
	public static final int MSG_GET_OTHER_USER_ICON = 101;
	Drawable dw =null;
    public int radioChecked=-1;
    
    private String o_uid = null ; 
    
    public Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
					showNetworkErrView(Constants.MSG_GET_FEEDS_NETWORK_ERROR) ;
					break;
					
				case Constants.MSG_GET_FOLLOWED_FINISH:
					progress_user_apps.setVisibility(View.GONE);
					refreshGridView(userFollowedThread.getFeeds());
					break;
					
				case Constants.MSG_GET_FANS_FINISH:
					progress_user_apps.setVisibility(View.GONE);
					refreshGridView(userFollowerThread.getFeeds());
					break;
					
				case Constants.MSG_GET_FEEDICON_FINISH:
					mAppGridView.invalidateViews();
					break;
					
				case Constants.MSG_GET_OTHER_USER_STATUS_OK:
					progress_user_apps.setVisibility(View.INVISIBLE);
					 ArrayList<AppInfo>otherUserApp = userAppThread.getUserApps();
					refreshOtherUsersAppGridView(otherUserApp);
					break;
					
				case Constants.MSG_GET_MY_STATUS_INFO_OK:
					refreshMyStatusInfo(userAppThread.getMyStatusInfo());
					break;
					
				case MSG_GET_OTHER_USER_ICON:
					img_user_icon.setImageDrawable(dw);
					if(!(LocalStore.getLocaleStoreInstance(UserAppActivity.this).
							UserIconShortCutCreated())){
						String shortName=LocalStore.getLocaleStoreInstance(
								UserAppActivity.this).getNickName();
						ActivityUtil.creatShortcut(UserAppActivity.this,shortName,dw,Constants.PACKAGENAME,"com.secneo.appshare.activities.UserAppActivity");
						LocalStore.getLocaleStoreInstance(UserAppActivity.this)
									.setUserIconShortCutCreated(true) ;
					}
					break;
				case Constants.GET_PRIVATE_MSG_FINISH:
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					int count = privateMsgThread.getList().size() ;
					for(int i = 0 ; i < count ; ++i){
						mPrivateMsgList.add(privateMsgThread.getList().get(i)) ;
					}
					if(count < 10){
						Toast.makeText(UserAppActivity.this, 
								R.string.msg_has_loaded, 
								Toast.LENGTH_SHORT).show() ;
						mMsgLoadOver = true ;
						mPrivateMsgPageIndex = 1 ;
					} 
					++mPrivateMsgPageIndex ;
					
					progress_user_apps.setVisibility(View.INVISIBLE) ;
					refreshPrivateMsgList() ;
					break ;
				case Constants.GET_PRIVATE_MSG_IMG_FINISH:
					mPrivateMsgListView.invalidateViews() ;
					break ;
				case Constants.GET_PRIVATE_MSG_BY_UID_FINISH:
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					progress_user_apps.setVisibility(View.INVISIBLE) ;
					int count1 = privateMsgThread.getList().size() ;
					for(int i = 0 ; i < count1 ; ++i){
						mPrivateMsgList.add(privateMsgThread.getList().get(i)) ;
					}
					if(count1 < 10){
						Toast.makeText(UserAppActivity.this, 
								R.string.msg_has_loaded, 
								Toast.LENGTH_SHORT).show() ;
						mMsgLoadOver = true ;
						mPrivateMsgPageIndex = 1 ;
					} 
					++mPrivateMsgPageIndex ;
					refreshPrivateMsgListByUid() ;
					break ;
				case Constants.GET_PRIVATE_MSG_IMG_BY_UID_FINISH:
					mPrivateMsgListView.invalidateViews() ;
					break ;
				case Constants.LOOK_PRIVATE_MSG_BY_UID:
					mDialogListShow = true ;
					adapter.setIsByUid(true) ;
					startGetSmsByUid(msg.getData().getString(Constants.UID_ACTION)) ;
					break ;
				case Constants.DELETE_PRIVATE_MSG_ACTION:
					String prompt1 = getResources().getString(
							R.string.delete_private_msg_ing) ;
					mDelMsgProgressBar = ProgressDialog.show(
	            			UserAppActivity.this, null,
	            			prompt1 ,true);
					Bundle data = msg.getData() ;
					int position = data.getInt("position") ;
					int msg_id = data.getInt(Constants.UID_ACTION) ;
					deleteMsg(position, msg_id) ;
					break ;
				case Constants.GET_PRIVATE_MSG_ERR:
					showNetworkErrView(Constants.GET_PRIVATE_MSG_ERR) ;
					break ;
				case Constants.GET_PRIVATE_MSG_BY_UID_ERR:
					showNetworkErrView(Constants.GET_PRIVATE_MSG_BY_UID_ERR) ;
					break;
				case Constants.DELETE_PRIVATE_MSG_FINISH:
					mDelMsgProgressBar.dismiss() ;
					Toast.makeText(UserAppActivity.this, 
							R.string.delete_msg_success, Toast.LENGTH_SHORT).show() ;
					mPrivateMsgListView.invalidateViews() ;
					break;
				case Constants.DELETE_PRIVATE_MSG_ERR:
					mDelMsgProgressBar.dismiss() ;
					Toast.makeText(UserAppActivity.this, 
							R.string.delete_msg_faild, Toast.LENGTH_SHORT).show() ;
					break;
				case Constants.GET_PRIVATE_MSG_NO_DATA:
					if(mDynDisPMProgressBar != null && 
							mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					if(mPrivateMsgPageIndex != 1){
						Toast.makeText(UserAppActivity.this, "内容已加载完毕", 
								Toast.LENGTH_SHORT).show() ;
						mMsgLoadOver = true ;
						mPrivateMsgPageIndex = 1 ;
					} else {
						progress_user_apps.setVisibility(View.INVISIBLE);
						mEmptyListPromptTV.setText(R.string.private_msg_empty) ;
						mEmptyListPromptTV.setVisibility(View.VISIBLE) ;
						enableToggleButtons(true) ;
					}
					break ;
				case Constants.GET_PRIVATE_MSG_BY_UID_NO_DATA:
					if(mDynDisPMProgressBar != null && 
							mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					if(mPrivateMsgPageIndex != 1){
						Toast.makeText(UserAppActivity.this, "内容已加载完毕", 
								Toast.LENGTH_SHORT).show() ;
						mMsgLoadOver = true ;
						mPrivateMsgPageIndex = 1 ;
					} else {
						progress_user_apps.setVisibility(View.INVISIBLE);
						mEmptyListPromptTV.setText(R.string.private_msg_empty) ;
						mEmptyListPromptTV.setVisibility(View.VISIBLE) ;
						enableToggleButtons(true) ;
					}
					break ;
				default:
					break ;
			}
			super.handleMessage(msg);
		}

	};
	
	private void deleteMsg(final int position , final int msg_id){
		
		new Thread(){
			public void run(){
				RemoteApiImpl rai = new RemoteApiImpl() ;
				if(rai.deleteMsg(LocalStore.getLocaleStoreInstance(
						UserAppActivity.this).getUid()
						, msg_id) == 1){
					Message msg = new Message() ;
					msg.what = Constants.DELETE_PRIVATE_MSG_FINISH ;
					mPrivateMsgList.remove(position) ;
					mHandler.sendMessage(msg) ;					
				} else {
					Message msg = new Message() ;
					msg.what = Constants.DELETE_PRIVATE_MSG_ERR ;
					mHandler.sendMessage(msg) ;
				}
			}
			
		}.start() ;
	}

	private void showNetworkErrView(int action){
		View view = UserAppActivity.this.findViewById(R.id.error_user);
		view.setVisibility(View.VISIBLE);
		progress_user_apps.setVisibility(View.INVISIBLE);
		enableToggleButtons(true);
	}
	
	public void refreshGridView(final Feeds feeds) 
	{
		if(feeds == null || (feeds != null && feeds.feeds.size() == 0)){
			if(currentControl == UserAppPage.MyFansPage){
				//无粉丝，提示。
				mEmptyListPromptTV.setText(R.string.txt_no_fllower) ;
			} else if(currentControl == UserAppPage.MyFlowPage){
				//无关注，提示。
				mEmptyListPromptTV.setText(R.string.txt_no_fllowed) ;
			}
			
			mEmptyListPromptTV.setVisibility(View.VISIBLE) ;		
		}

		feedAdapter = new FeedsAdapter(this, feeds.feeds);
		mAppGridView.setVisibility(View.VISIBLE);
		mAppGridView.setNumColumns(4);
		mAppGridView.setAdapter(feedAdapter);
		mAppGridView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try 
				{
					Feed userInfo = feeds.feeds.get(position);
					Intent intent = new Intent(); 
					intent.setClass(UserAppActivity.this, AppsOtherUserActivity.class);

					Bundle mBundle = new Bundle();
					String uid = LocalStore.getLocaleStoreInstance(UserAppActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putString("other_uid", userInfo.uid);
					mBundle.putString("user_icon", userInfo.user_icon);
					mBundle.putString("user_name", userInfo.user_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		enableToggleButtons(true);
	}
	

	private void startotherUserAppThread()
	{
		userAppThread = new UserAppThread(this, mHandler, uid, other_uid,0,0);
		userAppThread.start();
	}

	public void refreshOtherUsersAppGridView( ArrayList<AppInfo> ai)
	{
		mAppGridView.setVisibility(View.VISIBLE);
		mAppGridView.setNumColumns(4);
		mAppGridView.setAdapter(new UserAppAdapter(this, ai));
		enableToggleButtons(true);
		ApplicationGridViewListener listener = new ApplicationGridViewListener(ai);
		mAppGridView.setOnItemClickListener(listener);
	}
	
	public void refreshMyStatusInfo(OtherUserApps myInfo)
	{
		if(myInfo == null)
			return;
		
		int appNum = userAppThread.getUserApps().size();
		numInstallText.setText(String.valueOf(appNum));
		numShareText.setText(String.valueOf(myInfo.numShare));
		numFollowedText.setText(String.valueOf(myInfo.numFollowed));
		numFollowerText.setText(String.valueOf(myInfo.numFollower));

		TextView privateMsgNumber = (TextView) findViewById(R.id.private_msg_number);
		int sms_count = LocalStore.getLocaleStoreInstance().SMSCount() ;
		if(sms_count>99){
			sms_count = 99;
		}
		if(sms_count>0){
			privateMsgNumber.setVisibility(View.VISIBLE);
			privateMsgNumber.setText(""+sms_count);
		}
	}

	@Override
	protected void onResume()
	{
		Log.d("TAG", "UserAppActivity onResume start --- ") ;
		initShuzi();
		
		if(currentControl == UserAppPage.MyPrivateMsgPage)
			mPrivateMsgListView.invalidateViews();
		else
			mAppGridView.invalidateViews();
		Log.d("TAG", "UserAppActivity onResume end === ") ;
		super.onResume();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_user_app);
		
		Log.d("TAG", "UserAppActivity onCreate start --- ") ;
		
		AppShareApplication.getInstance().addActivity(this);
		new Thread()
		{
			public void run()
			{
				String ttt = getIntent().getStringExtra(Constants.NOTES_INTENT_ACTION);
				if (Constants.NOTES_INTENT_ACTION_TAG.equals(ttt))
				{
					NotificationManager myNotiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
					myNotiManager.cancel(R.string.app_name);
				}
			}
		}.start();

		TextView privateMsgNumber = (TextView) findViewById(R.id.private_msg_number);
		privateMsgNumber.setVisibility(View.INVISIBLE);
		btnPrivateMessage = (Button) findViewById(R.id.btn_private_message);
		btnPrivateMessage.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2008);
				dh.close();
				startGetMySms(true);
				return;
			}
		}) ;
		

		mBottomButtonLayout = (LinearLayout) findViewById(R.id.bottom_button_layout);
		
		mAppGridView = (GridView) findViewById(R.id.grid_apps);
		label_user_name = (TextView) findViewById(R.id.label_user_name);
		phone_type = (TextView) findViewById(R.id.phone_type);
		img_user_icon = (ImageView) findViewById(R.id.img_user_icon);
		weibo_Icon = (ImageView) findViewById(R.id.weibo_Icon);
		progress_user_apps = (ProgressBar) findViewById(R.id.progress_user_apps);
		myInfoLinear = (LinearLayout) findViewById(R.id.panel_top);

		int snsResource = LocalStore.getLocaleStoreInstance().getLocalSnsIconResource();
		if(snsResource != 0)
		{
			weibo_Icon.setImageResource(snsResource);
			weibo_Icon.setVisibility(View.VISIBLE);
		}
		else
		{
			weibo_Icon.setVisibility(View.INVISIBLE);
		}
		
		initShuzi() ;
		
		RemindCountThread t = new RemindCountThread(this, mHandler) ;
		t.start() ;
		
		buttonApp = (Button) findViewById(R.id.button_app);
		buttonApp.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2006);
				dh.close();
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneAttentActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		buttonFollowed = (Button) findViewById(R.id.button_followed);
		buttonFollowed.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2007);
				dh.close();
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneFansActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		buttonFollower = (Button) findViewById(R.id.button_follower);
		buttonFollower.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2036);
				dh.close();
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneHonorActivity.class);
				Bundle mBundle = new Bundle();
				intent.putExtras(mBundle);
				startActivity(intent);
				return;
			}
		}) ;
		buttonSms = (Button) findViewById(R.id.button_sms);
		buttonSms.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2037);
				dh.close();
				Intent intent = new Intent() ;
				intent.setClass(UserAppActivity.this, RemindActivity.class) ;
				Bundle mBundle = new Bundle();
				mBundle.putInt("action_type", Constants.actionTypeMine);
				mBundle.putString("userid", LocalStore.getLocaleStoreInstance().getUid());
				mBundle.putString("username", LocalStore.getLocaleStoreInstance().getNickName());
				mBundle.putString("avatarname", LocalStore.getLocaleStoreInstance().getAvatarName());
				intent.putExtras(mBundle);
				startActivity(intent) ;
				return;
			}
		}) ;
		
		

		numInstallText = (TextView) findViewById(R.id.num_install);
		numInstallText.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
			}
		}) ;
		numShareText = (TextView) findViewById(R.id.num_share);
		numShareText.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent() ;
				intent.setClass(UserAppActivity.this, RemindActivity.class) ;
				Bundle mBundle = new Bundle();
				mBundle.putInt("action_type", Constants.actionTypeMine);
				mBundle.putString("userid", LocalStore.getLocaleStoreInstance().getUid());
				mBundle.putString("username", LocalStore.getLocaleStoreInstance().getNickName());
				mBundle.putString("avatarname", LocalStore.getLocaleStoreInstance().getAvatarName());
				intent.putExtras(mBundle);
				startActivity(intent) ;
				return;
			}
		}) ;
		numFollowedText = (TextView) findViewById(R.id.num_followed);
		numFollowedText.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneAttentActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		numFollowerText = (TextView) findViewById(R.id.num_follower);
		numFollowerText.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneFansActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		


		textInstall = (TextView) findViewById(R.id.word_install);
		textInstall.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
			}
		}) ;
		textShare = (TextView) findViewById(R.id.word_share);
		textShare.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent() ;
				intent.setClass(UserAppActivity.this, RemindActivity.class) ;
				Bundle mBundle = new Bundle();
				mBundle.putInt("action_type", Constants.actionTypeMine);
				mBundle.putString("userid", LocalStore.getLocaleStoreInstance().getUid());
				mBundle.putString("username", LocalStore.getLocaleStoreInstance().getNickName());
				mBundle.putString("avatarname", LocalStore.getLocaleStoreInstance().getAvatarName());
				intent.putExtras(mBundle);
				startActivity(intent) ;
				return;
			}
		}) ;
		textFollowed = (TextView) findViewById(R.id.text_followed);
		textFollowed.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneAttentActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		textFollower = (TextView) findViewById(R.id.text_follower);
		textFollower.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, MyZoneFansActivity.class);
				startActivity(intent);
				return;
			}
		}) ;
		
		
		paixu = (Button) findViewById(R.id.paixu);
		paixu.setVisibility(View.VISIBLE);
		paixu.setOnClickListener(mPaixuListener);
		
		mRetIv = (Button)findViewById(R.id.img_ret) ;
		mRetIv.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if(mDialogListShow){
					mDialogListShow = false ;
					if(adapter != null )
						adapter.setIsByUid(false) ;
					initListAssData() ;
					startGetMySms(false) ;
				} 
				else if(UserAppPage.MyPrivateMsgPage==currentControl){
					mBottomButtonLayout.setVisibility(View.VISIBLE);
					startGetMyApp();
				}
				else {
					finish();
				}
			}
		}) ;
		mTopbarTv = (TextView)findViewById(R.id.topbar_txt) ;
				
		mPrivateMsgListView = (ListView) findViewById(R.id.private_msg_list) ;
		mPrivateMsgListView.setDivider(new ColorDrawable(Color.TRANSPARENT));
		mPrivateMsgListView.setVisibility(View.INVISIBLE) ;
		mPrivateMsgListView.setOnScrollListener(listScrollListener) ;
		
		mEmptyListPromptTV = (TextView)findViewById(R.id.empty_list_prompt) ;

		label_user_name.setText(LocalStore.getLocaleStoreInstance().getNickName());
        String phoneTypeString = "(<u>"+Build.MODEL+"</u>)";
		phone_type.setText(Html.fromHtml(phoneTypeString)); 
		phone_type.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
				dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2045);
				dh.close();
				
				Intent intent = new Intent() ;
				intent.setClass(UserAppActivity.this, PhoneUsersActivity.class) ;
				Bundle mBundle = new Bundle();
				mBundle.putString("phonename", Build.MODEL);
				intent.putExtras(mBundle);
				startActivity(intent) ;
				return;
			}
		});
		
		String user_image=LocalStore.getLocaleStoreInstance().getAvatarName();
		Log.d("MyTag", " user_name = "+LocalStore.getLocaleStoreInstance().getNickName());
		Log.d("MyTag", "user_image = " + user_image ) ;
		if(!"".equals(user_image) && user_image!=null)
		{
			if(user_image.contains("buildin"))
			{
				try {
					dw= Util.getDrawableFromAsset(this, user_image);
				} catch (IOException e) {
					e.printStackTrace();
				}
				Message msg = new Message();
				msg.what = UserAppActivity.MSG_GET_OTHER_USER_ICON;
				mHandler.sendMessage(msg);
			}
			else
			{	
				UserAppIconThread	userAppIconThread = new UserAppIconThread(this, mHandler,user_image);
				userAppIconThread.start();
			}
			
		}
		
		currentControl = UserAppPage.MyAppPage ;
		
		
		Log.d("TAG", "UserAppActivity onCreate end --- ") ;
	}

	private OnScrollListener listScrollListener = new ListView.OnScrollListener(){
		
        @Override
        public void onScroll(AbsListView arg0,
                    int firstVisibleItem, int visibleItemCount, 
                    int totalItemCount) {
            if (totalItemCount <= 0){
            	return;
            }
        }
       
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        	if (view.getLastVisiblePosition() == view.getCount() - 1 &&
        			scrollState == OnScrollListener.SCROLL_STATE_IDLE) {    
            	if(mMsgLoadOver){
            		return ;
            	}
            	if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
            		return ;
            	}
            	String prompt1 = getResources().getString(
						R.string.get_private_msg_ing) ;
            	mDynDisPMProgressBar = ProgressDialog.show(
            			UserAppActivity.this, null, prompt1 ,true);
            	if(mDialogListShow){
            		privateMsgThread = new PrivateMsgThread(UserAppActivity.this , mHandler , 
            				LocalStore.getLocaleStoreInstance(UserAppActivity.this).getUid() , o_uid , true ,
            				mPrivateMsgPageIndex) ;
            	} else {
            		privateMsgThread = new PrivateMsgThread(UserAppActivity.this , mHandler , 
            				LocalStore.getLocaleStoreInstance(UserAppActivity.this).getUid() , null , false ,
            				mPrivateMsgPageIndex) ;
            	}
            	
            	privateMsgThread.start() ;
            }
        }
	};
	
	private void initReceiver(){
		try
		{
	        mRemindReciver = new RemindReciver();  
	        IntentFilter filter = new IntentFilter();  
	        filter.addAction(Constants.REMIND_ACTION);  
	        registerReceiver(mRemindReciver, filter); 
        
		}catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	private void initShuzi(){
		
		mShuziFollower = (TextView) findViewById(R.id.shuzi_follower) ;
		mShuziHonor = (TextView) findViewById(R.id.shuzi_honor) ;
		int follower_count = LocalStore.getLocaleStoreInstance().FollowerCount() ;
		if(follower_count>99){
			follower_count = 99;
		}
		if(follower_count == 0){
			mShuziFollower.setVisibility(View.INVISIBLE) ;
		} else {
			mShuziFollower.setVisibility(View.VISIBLE);
			mShuziFollower.setText(""+follower_count);
		}
		
		int honor_count = LocalStore.getLocaleStoreInstance().honorCount() ;
		Log.d("MyTag", "honor_count="+honor_count);
		if(honor_count>99){
			honor_count = 99;
		}
		if(honor_count == 0){
			mShuziHonor.setVisibility(View.INVISIBLE) ;
		} else {
			mShuziHonor.setVisibility(View.VISIBLE);
			mShuziHonor.setText(honor_count+"");
		}
	}
	

	@Override
	protected void onStop()
	{
		try
		{
			if(mRemindReciver != null)
				unregisterReceiver(mRemindReciver);
			
		}catch (Exception ex)
		{
			ex.printStackTrace();
		}
		super.onStop();
	}

	
	class ApplicationGridViewListener implements OnItemClickListener
	{
		private  ArrayList<AppInfo> mList;

		public ApplicationGridViewListener( ArrayList<AppInfo> list)
		{
			this.mList = list;
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			try
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(UserAppActivity.this, ApplicationActivity.class);
				ApplicationInfo app = mList.get(position).appInfo;

				Bundle mBundle = new Bundle();
				mBundle.putString("package_name", app.packageName);
				mBundle.putInt("n", 20);
				String uid = LocalStore.getLocaleStoreInstance(UserAppActivity.this).getUid();
				mBundle.putString("uid", uid);
				mBundle.putBoolean("installed_not_addicted", true);

				mBundle.putString("app_icon", "");
				
				mBundle.putBoolean("user_app_flag", true);
				pm = UserAppActivity.this.getPackageManager();
				Drawable dw = app.loadIcon(pm);
				if (dw != null)
				{
					try
					{
						Bitmap bitmap = ((BitmapDrawable) dw).getBitmap();
						ByteArrayOutputStream stream = new ByteArrayOutputStream();

						bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
						byte[] bitmapdata = stream.toByteArray();
						mBundle.putByteArray("app_icon_array", bitmapdata);
					} catch (Exception ex)
					{
						ex.printStackTrace();
						mBundle.putByteArray("app_icon_array", null);
					}

				} else
				{
					mBundle.putByteArray("app_icon_array", null);
				}
				mBundle.putString("app_name", app.loadLabel(pm).toString().trim());
				intent.putExtras(mBundle);
				startActivity(intent);

			} catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
	}
	
	public class UserAppIconThread extends Thread 
	{
		private Context ctx;
		private Handler handler;
		private List<ApplicationInfo> otherUserApp;
		private String appIconurl;
		public UserAppIconThread(Context ctx, Handler handler,String appIconurl) 
		{
			this.ctx = ctx;
			this.handler = handler;
			this.appIconurl=appIconurl;
		}
		
		public List<ApplicationInfo>  getUserApps() 
		{
			return otherUserApp;
		}
		
		public void run() 
		{
			try 
			{
				dw = Util.getDrawableFromCache(ctx, appIconurl);
				if(dw == null)
					dw = getResources().getDrawable(R.drawable.some_user) ;

				Message msg = new Message();
				msg.what = UserAppActivity.MSG_GET_OTHER_USER_ICON;
				handler.sendMessage(msg);
				
			} catch(Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	
	
	// 获得我安装的应用程序列表
	private void startGetMyApp(){
		hideCurrentPage() ;
		mTopbarTv.setText(R.string.my_app) ;
		myInfoLinear.setVisibility(View.VISIBLE);
		currentControl = UserAppPage.MyAppPage ;		
		 ArrayList<AppInfo> otherUserApp = userAppThread.getUserApps();
		refreshOtherUsersAppGridView(otherUserApp);
		mAppGridView.setVisibility(View.VISIBLE) ;
	}
	
	
	// 获得我的私信列表
	private void startGetMySms(boolean hide_flag)
	{
		if (hide_flag)
			hideCurrentPage();

		LocalStore.getLocaleStoreInstance(this).setSMSCounts(0);

		mTopbarTv.setText(R.string.my_private_msg);
		mBottomButtonLayout.setVisibility(View.GONE);
		currentControl = UserAppPage.MyPrivateMsgPage;

		progress_user_apps.setVisibility(View.VISIBLE);
		privateMsgThread = new PrivateMsgThread(this, mHandler, LocalStore.getLocaleStoreInstance(this).getUid(), null, false, mPrivateMsgPageIndex);
		privateMsgThread.start();
	}
	
	// 获得对话
	private void startGetSmsByUid(String uid){
		o_uid = uid ;
		
		mPrivateMsgListView.setVisibility(View.INVISIBLE);	//隐藏listview
		progress_user_apps.setVisibility(View.VISIBLE) ;	//显示滚动条

		initListAssData() ;
		
		privateMsgThread = new PrivateMsgThread(this , mHandler , 
				LocalStore.getLocaleStoreInstance(this).getUid() , uid , true ,
				1) ;
		privateMsgThread.start() ;
	}
	
	private void refreshPrivateMsgList(){
		mPrivateMsgListView.setVisibility(View.VISIBLE);
		if(adapter == null){
			adapter = new PrivateMsgListAdapter(
					this, mPrivateMsgList ,mHandler , false) ;
			mPrivateMsgListView.setAdapter(adapter);
		}
		else {
			adapter.setList((List<PrivateMsg>)mPrivateMsgList) ;
			adapter.notifyDataSetChanged() ;
		}
		
		int size = mPrivateMsgList.size() ;
		if(size > 10){
			if(size % 10 == 0){
				size -= 1 ;
			}
			mPrivateMsgListView.setSelection((size / 10) * 10) ;
		}
		enableToggleButtons(true);
	}
	
	private void refreshPrivateMsgListByUid(){
		mPrivateMsgListView.setVisibility(View.VISIBLE);
		if(adapter == null){
			adapter = new PrivateMsgListAdapter(this, 
					mPrivateMsgList ,mHandler , true) ;
			mPrivateMsgListView.setAdapter(adapter);
		}else{
			adapter.setList((List<PrivateMsg>)mPrivateMsgList) ;
			adapter.notifyDataSetChanged() ;
		}
		enableToggleButtons(true);
	}
	
	private void initListAssData(){
		mMsgLoadOver = false ;
		mPrivateMsgList.clear() ;
		mPrivateMsgPageIndex = 1 ;
	}
	
	private void hideCurrentPage(){
		switch(currentControl){
		case MyAppPage:
			progress_user_apps.setVisibility(View.INVISIBLE);
			mAppGridView.setVisibility(View.INVISIBLE) ;
			myInfoLinear.setVisibility(View.GONE);
			break ;
		case MyFlowPage:
			progress_user_apps.setVisibility(View.INVISIBLE);
			mAppGridView.setVisibility(View.INVISIBLE) ;
			myInfoLinear.setVisibility(View.GONE);
			if (userFollowedThread != null && userFollowedThread.isAlive())
				userFollowedThread.stopRun();
			break ;
		case MyFansPage:
			progress_user_apps.setVisibility(View.INVISIBLE);
			mAppGridView.setVisibility(View.INVISIBLE) ;
			myInfoLinear.setVisibility(View.GONE);
			if (userFollowerThread != null && userFollowerThread.isAlive())
				userFollowerThread.stopRun();
			break ;
		case MyPrivateMsgPage:
			initListAssData() ;
			
			progress_user_apps.setVisibility(View.INVISIBLE);
			if(privateMsgThread != null &&privateMsgThread.isAlive()){
				privateMsgThread.stopRun() ;
				privateMsgThread = null ;
			}
			mPrivateMsgListView.setVisibility(View.GONE) ;
			break ;
		}
	}

	class RemindReciver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {

			int fans = intent.getIntExtra(Constants.NEW_FANS_COUNT_TAG , 0) ;
			if(fans>99){
				fans = 99;
			}
			if(fans == 0){
				mShuziFollower.setVisibility(View.INVISIBLE) ;
			} else {
				mShuziFollower.setVisibility(View.VISIBLE);
				mShuziFollower.setText(""+fans);
			}
			int activity = intent.getIntExtra(Constants.NEW_Activity_COUNT_TAG , 0) ; 
			int sms = intent.getIntExtra(Constants.NEW_MSG_COUNT_TAG , 0) ;
		}
	}
	
	private void enableToggleButtons(boolean enable)
	{
		return;
	}
	
	/* 程序排序 */
	private final OnClickListener mPaixuListener = new OnClickListener() 
	{
		@Override
		public void onClick(View v) 
		{
			DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
			dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2003);
			dh.close();
			new AlertDialog.Builder(UserAppActivity.this).setIcon(
					android.R.drawable.ic_dialog_alert).setTitle("排序")
					.setSingleChoiceItems(new String[] { "使用频率", "安装时间" },
							radioChecked, new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which)

								{
									radioChecked = which;
									Log.d("which", "which="+which+"radioChecked"+radioChecked);
									if(which==0)
									{
										DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
										dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2004);
										dh.close();
										userAppThread = new UserAppThread(UserAppActivity.this, mHandler, uid, other_uid,1,-1);
										userAppThread.start();
									}
									if(which==1)
									{
										DatabaseHelper dh=new DatabaseHelper(UserAppActivity.this);
										dh.insertUserAppPopularityBycatagory(UserAppActivity.this,2005);
										dh.close();
										userAppThread = new UserAppThread(UserAppActivity.this, mHandler, uid, other_uid,2,-1);
										userAppThread.start();
									}
									dialog.dismiss();
								}

							}).create().show();
		}
	};

	@Override
	protected void onStart() 
	{
		Log.d("TAG", "UserAppActivity onStart start --- ") ;
		o_uid = null ;
		initReceiver() ;
		if(currentControl == UserAppPage.MyAppPage)
		{
			initListAssData() ;
			startotherUserAppThread();
		}
		Log.d("TAG", "UserAppActivity onStart end --- ") ;
		super.onRestart();
	}

	
	
	@Override
	protected void onDestroy() 
	{
		mAppGridView.setAdapter(null);
		if(feedAdapter != null)
		{
			feedAdapter.freeDrawable();
			feedAdapter=null;
		}
		mPrivateMsgListView.setAdapter(null);
		if(adapter != null)
		{
			adapter.freeDrawable();
			adapter=null;
		}
		super.onDestroy();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			if(mDialogListShow){
				mDialogListShow = false ;
				if(adapter != null )
					adapter.setIsByUid(false) ;
				initListAssData() ;
				startGetMySms(false) ;
				View view = UserAppActivity.this.findViewById(R.id.error_user);
				view.setVisibility(View.INVISIBLE);
				mEmptyListPromptTV.setVisibility(View.INVISIBLE) ;
				if(privateMsgThread.isAlive())
					privateMsgThread.interrupt() ;
				enableToggleButtons(false) ;
				return true;
			} 
			else if(UserAppPage.MyPrivateMsgPage==currentControl){
				mBottomButtonLayout.setVisibility(View.VISIBLE);
				paixu.setVisibility(View.VISIBLE);
				startGetMyApp();
				return true;
			}
			else {
				return super.onKeyDown(keyCode, event) ;
			}
		} else {
			return super.onKeyDown(keyCode, event) ;
		}
		
	}		
}
